<template>
  <div>
    <JwChat-index
      :taleList="taleList"
      @enter="bindEnter"
      v-model="inputMsg"
      :showRightBox='true'
      scrollType="noscroll"
      :config="config"
    >
      <template v-for="(user,index) in userList">
        <div style="margin: 10px 0px;padding: 10px 0px" v-bind:class="{uerListBackground:currentIndex==index}">
          <JwChat-item :config="user" @click="bindClick($event,index)" />
        </div>

      </template>
    </JwChat-index>
  </div>
</template>

<script>
export default {
  name: "index",
  data() {
      return {
          userId:'',
          inputMsg: '',
          taleList: [
          ],
          tool: {
              // show: ['file', 'history', 'img', ['文件1', '', '美图']],
              // showEmoji: false,
              callback: this.toolEvent
          },
          config: {
              img: require("@/assets/images/userImageClient.jpg"),
              name: '客服',
              dept: '客服001',
              callback: this.bindCover,
              historyConfig:{
                  show: true,
                  tip: '加载更多',
                  callback: this.bindLoadHistory,
              }
          },
          userList:[],
          ws:"",
          userBackground:false,
          currentIndex: -1
      }
  },
    methods: {
        bindEnter () {
            let date = new Date()
            var dateTime = this.dateFormat("YYYY-mm-dd HH:MM", date)
            const msg = this.inputMsg;
            if (!msg) return;
            const msgObj = {
                "date": dateTime,
                "text": { "text": msg },
                "mine": true,
                "name": "客服",
                "img": require("@/assets/images/userImageClient.jpg")
            }

            for(var i=0;i<this.userList.length;i++){
                if(this.userList[i].uid == this.userId){
                    this.userList[i].manageList.push(msgObj);
                    //调用socket发送
                    var userId = sessionStorage.getItem("userId");
                    var mesage = {
                        userId:userId,
                        text:msg,
                        type:1,
                        destinationId:this.userId
                    }
                    var messageJson = JSON.stringify(mesage);
                    this.ws.send(messageJson);
                }
            }
        },
        /**
         * @description:
         * @param {*} type 当前点击的按钮
         * @param {*} plyload 附加文件或者需要处理的数据
         * @return {*}
         */
        toolEvent (type, plyload) {
            console.log('tools', type, plyload)
        },
        /**
         * @description: 点击加载更多的回调函数
         * @param {*}
         * @return {*}
         */
        bindLoadHistory () {
            const history = new Array(3).fill().map((i, j) => {
                return {
                    "date": "2020/05/20 23:19:07",
                    "text": { "text": j + new Date() },
                    "mine": false,
                    "name": "JwChat",
                    "img": "image/three.jpeg"
                }
            })
            let list = history.concat(this.list)
            this.list = list
            console.log('加载历史', list, history)
        },
        bindCover (type) {
            console.log('header', type)
        },
        bindClick(even,index){
            //用户id
            console.log("index",index);
            var userId = even.value.uid;
            this.userId = userId;
            this.taleList = even.value.manageList;
            console.log("点击",even);
            this.currentIndex = index;
        },
        init(){
            //客服
            var userId = sessionStorage.getItem("userId");
            if(userId == null || userId == undefined || userId == ''){
                userId = this.getUuid();
                sessionStorage.setItem("userId",userId);
            }
            this.ws = new WebSocket(process.env.VUE_APP_WS_URL+"/api/messageSocket");
            var mesage = {
                userId:userId,
                text:'',
                type:1,
                destinationId:''
            }
            var then = this;
            this.ws.onopen = function(evt) {  //绑定连接事件
                console.log("Connection open ...");
                var messageJson = JSON.stringify(mesage);
                console.log(messageJson)
                then.ws.send(messageJson);
            };
            this.ws.onmessage = function(evt) {//绑定收到消息事件
                console.log( "Received Message: " + evt.data);
                var data = JSON.parse(evt.data);

                if(data.userId !=undefined && data.userId !=null && data.userId !=''){
                    mesage.destinationId = data.userId;
                }
                var count = 0;
                for(var i=0;i<then.userList.length;i++){
                    if(then.userList[i].uid == data.userId){
                        var message = {
                            "date": data.dateTime,
                            "text": { "text": data.text },
                            "mine": false,
                            "name": "客户001",
                            "img": require("@/assets/images/userImage.jpg")
                        }
                        then.userList[i].manageList.push(message);
                        count++;
                    }
                }
                if(count == 0){
                    //添加新的用户
                    var user1 = {
                        uid:data.userId,
                        img: require("@/assets/images/userImage.jpg"),
                        name: '客户001',
                        callback: this.bindCover,
                        historyConfig:{
                            show: true,
                            tip: '加载更多',
                            callback: this.bindLoadHistory,
                        },
                        manageList:[
                            {
                                "date": data.dateTime,
                                "text": { "text": data.text },
                                "mine": false,
                                "name": "客户001",
                                "img": require("@/assets/images/userImage.jpg")
                            }
                        ]
                    }
                    then.userList.push(user1);
                }

            };

            this.ws.onclose = function(evt) { //绑定关闭或断开连接事件
                console.log("Connection closed.");
            };
        },
        getUuid() {
          var s = [];
          var hexDigits = "0123456789abcdef";
          for (var i = 0; i < 36; i++) {
              s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
          }
          s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
          s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
          s[8] = s[13] = s[18] = s[23] = "-";

          var uuid = s.join("");
          return uuid;
        },
        //获取日期
        dateFormat(fmt, date) {
          let ret;
          const opt = {
              "Y+": date.getFullYear().toString(),        // 年
              "m+": (date.getMonth() + 1).toString(),     // 月
              "d+": date.getDate().toString(),            // 日
              "H+": date.getHours().toString(),           // 时
              "M+": date.getMinutes().toString(),         // 分
              "S+": date.getSeconds().toString()          // 秒
              // 有其他格式化字符需求可以继续添加，必须转化成字符串
          };
          for (let k in opt) {
              ret = new RegExp("(" + k + ")").exec(fmt);
              if (ret) {
                  fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
              };
          };
          return fmt;
        }
    },
    created() {
    },
    mounted() {
      this.init();
    }

};
</script>

<style scoped lang="scss">
.home {
  blockquote {
    padding: 10px 20px;
    margin: 0 0 20px;
    font-size: 17.5px;
    border-left: 5px solid #eee;
  }
  hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eee;
  }
  .col-item {
    margin-bottom: 20px;
  }

  ul {
    padding: 0;
    margin: 0;
  }

  font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;

  ul {
    list-style-type: none;
  }

  h4 {
    margin-top: 0px;
  }

  h2 {
    margin-top: 10px;
    font-size: 26px;
    font-weight: 100;
  }

  p {
    margin-top: 10px;

    b {
      font-weight: 700;
    }
  }

  .update-log {
    ol {
      display: block;
      list-style-type: decimal;
      margin-block-start: 1em;
      margin-block-end: 1em;
      margin-inline-start: 0;
      margin-inline-end: 0;
      padding-inline-start: 40px;
    }
  }
}
  .uerListBackground {
    background-color: #00afff;
  }
</style>

